package com.wantup;

import org.apache.log4j.helpers.ThreadLocalMap;

import java.util.HashMap;
import java.util.UUID;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/6/19 17:44
 */
public class TestMain {

    private static ThreadLocal<Object> threadLocal = new ThreadLocal<>();


    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
        //不安全的map集合
        //unSafeMap();
        new Thread(new MyIntergerThread("one")).start();
        new Thread(new MyIntergerThread("two",11)).start();
    }

    public static class MyIntergerThread implements Runnable {

        private String name;
        private Integer num;


        public MyIntergerThread(String name) {
            this.name = name;
            this.num = 0;
        }

        public MyIntergerThread(String name, Integer num) {
            this.name = name;
            this.num = num;
        }

        @Override
        public void run() {

            for (int i = 0; i < 10; i++) {

                if (TestMain.threadLocal.get() == null) {
                    TestMain.threadLocal.set(num);
                    System.out.println("线程 : " + name + " 初始化值  --> " + num);

                } else {
                    int value = (Integer) TestMain.threadLocal.get();
                    TestMain.threadLocal.set(value + 1);
                    System.out.println("线程 : " + name +" 修改值  -->  "+TestMain.threadLocal.get());
                }


            }

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }


    private static void unSafeMap() {
        HashMap<String, String> hashMap = new HashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread() {
                @Override
                public void run() {
                    //System.out.println(Thread.currentThread().getName());
                    hashMap.put(UUID.randomUUID().toString().substring(0, 8), UUID.randomUUID().toString().substring(0, 8));
                    System.out.println(hashMap);
                }
            }.start();
        }
    }


}
